﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.ServiceImpl.Repositories.Interface;

namespace EzDesk.Core.ServiceImpl.Repositories
{
    public partial class PermissionRepository : IPermissionRepository
    {
        public bool GroupHasPermission(Guid permissionId, Guid userId)
        {
            bool hasPermission = false;
            ez_Permission permission = _db.ez_Permissions.Where(p => p.PermissionId == permissionId).Single();
            // 默认拒绝为false, 即默认有权限
            hasPermission = permission.DefaultDeny == false;

            var permission_groups =
                _db.ez_Permission_Groups
                .Where(p => p.GroupId == userId && p.PermissionId == permissionId)
                .SingleOrDefault();
            if (permission_groups != null)
            {
                hasPermission = permission_groups.HasPermission;
            }

            return hasPermission;
        }

        public void SetGroupPermission(Guid permissionId, Guid groupId, bool hasPermission)
        {
            var permission_user = _db.ez_Permission_Groups
                .Where(p => p.PermissionId == permissionId && p.GroupId == groupId)
                .SingleOrDefault();

            if (permission_user != null)
            {
                permission_user.HasPermission = hasPermission;
            }
            else
            {
                var permission_userEntity = new ez_Permission_Group()
                {
                    PermissionId = permissionId,
                    GroupId = groupId,
                    HasPermission = hasPermission,
                };
                _db.ez_Permission_Groups.InsertOnSubmit(permission_userEntity);
            }
            this.SaveChanges();
        }

    }
}
